package nsq

import (
	"context"
	"encoding/json"
	core "ez/apps/core/document"
	"ez/apps/core/service"
	"gitee.com/dreamwood/ez-go/ez"
	"gitee.com/dreamwood/ez-go/ss"
	"strings"
)

func init() {
	ez.Subscribe(ez.EventAfterServerRun, func(v interface{}, ctx context.Context) {
		//服务注册监听
		ez.CreateNsqHandler(ez.EzTopicReg, "default", func(content []byte) error {
			info := ez.CreatInfoFromBytes(content)
			//ez.JsonLog(info)
			service.RegHost(info)
			return nil
		})
		//服务心跳监听
		ez.CreateNsqHandler(ez.EzTopicHeartBeat, "default", func(content []byte) error {
			info := ez.CreatInfoFromBytes(content)
			service.HostHeartBeat(info)
			return nil
		})
		//接口数据监听
		ez.CreateNsqHandler(ez.EzTopicRegApi, "default", func(content []byte) error {
			tmp := strings.Fields(string(content))
			if len(tmp) > 1 {
				find, _ := core.NewApiCrud().FindOneBy(ss.M{
					"app":   tmp[0],
					"route": tmp[1],
				}, nil)
				if find.Id == 0 {
					find.App = tmp[0]
					find.Route = tmp[1]
					if len(tmp) > 2 {
						find.Name = tmp[2]
					}
					_ = find.Save()
					println("注册接口：" + tmp[0] + " " + tmp[1])
				}
			}
			return nil
		})
		//接口数据监控
		ez.CreateNsqHandler(ez.EzTopicRequestLog, "default", func(content []byte) error {
			log := new(core.RequestLog)
			e := json.Unmarshal(content, &log)
			if e != nil {
				ez.LogToConsole(e.Error())
				return e
			}
			ez.Try(log.Save())
			return nil
		})
	})
}
